﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace TimeMachine.Engine.Agents
{
	public class CsvWriter : IDisposable
	{
		private readonly TextWriter writer;
		private readonly char separator;
		private readonly bool ownWriter;
		private bool firstFieldInRow = true;

		public CsvWriter(TextWriter writer)
			: this(writer, ';', true)
		{
		}

		public CsvWriter(TextWriter writer, char separator, bool ownWriter)
		{
			this.writer = writer;
			this.separator = separator;
			this.ownWriter = ownWriter;
		}

		public void WriteField(string rawField)
		{
			if (!firstFieldInRow) writer.Write(separator);
			else firstFieldInRow = false;
			writer.Write(Escape(rawField));
		}

		private string Escape(string rawField)
		{
			rawField = rawField.Replace("\"", "\"\"");
			if(rawField.IndexOf(separator) >= 0 || rawField.Contains(Environment.NewLine))
				rawField = '\"' + rawField + '\"';
			return rawField;
		}

		public void WriteNextLine()
		{
			writer.WriteLine();
			firstFieldInRow = true;
		}

		public void Dispose()
		{
			if (ownWriter) writer.Dispose();
		}
	}
}